package com.itheima.api.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.api.orderother.OmsOrderItemService;
import com.itheima.api.orderother.OmsOrderOperateHistoryService;
import com.itheima.mapper.order.OmsOrderMapper;
import com.itheima.vo.dto.OrderDto;
import com.itheima.vo.pojo.OmsOrder;
import com.itheima.vo.pojo.OmsOrderItem;
import com.itheima.vo.pojo.OmsOrderOperateHistory;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@DubboService
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements OmsOrderService {

    @Autowired
    private OmsOrderMapper orderMapper;

    @DubboReference
    private OmsOrderService orderService;

    @DubboReference
    private OmsOrderItemService orderItemService;

    @DubboReference
    private OmsOrderOperateHistoryService operateHistoryService;


    /**
     * 分页条件查询
     *
     * @param pageNum
     * @param pageSize
     * @param orderSn
     * @param receiverKeyword
     * @param status
     * @param orderType
     * @param sourceType
     * @param createTime
     * @return
     */
    public Map list(Integer pageNum, Integer pageSize, String orderSn, String receiverKeyword,
                    Integer status, Integer orderType, Integer sourceType, String createTime) {
        //创建分页构造器
        Page<OmsOrder> page = new Page<>(pageNum, pageSize);

        //创建条件查询器
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.like(orderSn != null, OmsOrder::getOrderSn, orderSn);
        lqw.eq(status != null, OmsOrder::getStatus, orderSn);
        lqw.eq(orderType != null, OmsOrder::getOrderType, orderType);
        lqw.eq(sourceType != null, OmsOrder::getSourceType, sourceType);
        lqw.eq(createTime != null, OmsOrder::getCreateTime, createTime);
        if (receiverKeyword != null) {
            Boolean number = isNumber(receiverKeyword);
            if (number) {
                lqw.like(OmsOrder::getReceiverPhone, receiverKeyword);
                orderMapper.selectPage(page, lqw);
            } else {
                lqw.like(OmsOrder::getReceiverName, receiverKeyword);
                orderMapper.selectPage(page, lqw);
            }
        } else {
            orderMapper.selectPage(page, lqw);
        }

        Map map = new HashMap();
        map.put("list", page.getRecords());
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("total", page.getTotal());
        map.put("totalPage", page.getPages());

        return map;
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    public void delete(List<Integer> ids) {
        //创建条件构造器
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids != null, OmsOrder::getId, ids);
        orderService.remove(lqw);
    }

    /**
     * 批量关闭订单
     * @param ids
     * @param note
     */
    public void updateStatus(List<Integer> ids,String note) {
        List<OmsOrderOperateHistory> historyList = ids.stream().map(id -> {
            OmsOrder omsOrder = orderService.getById(id);
            if (omsOrder != null) {
                omsOrder.setNote(note);
                omsOrder.setStatus(4);
            }
            orderService.updateById(omsOrder);

            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(id);
            history.setCreateTime(LocalDateTime.now());
            history.setOperateMan("后台管理员");
            history.setOrderStatus(4);
            history.setNote("订单关闭:" + note);
            return history;
        }).collect(Collectors.toList());
        operateHistoryService.saveBatch(historyList);
    }

    /**
     * 批量发货
     *
     * @param list
     */
    public void delivery(List<OmsOrder> list) {
        //获取参数
        List<OmsOrderOperateHistory> historyList = list.stream().map(itmt -> {
            orderService.updateById(itmt);
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(itmt.getOrderId());
            history.setCreateTime(LocalDateTime.now());
            history.setOperateMan("后台管理员");
            history.setOrderStatus(2);
            history.setNote("完成发货");
            return history;
        }).collect(Collectors.toList());
        operateHistoryService.saveBatch(historyList);
    }

    /**
     * 修改订单费用信息
     *
     * @param order
     */
    public void moneyInfo(OmsOrder order) {
        //设置时间
        order.setModifyTime(LocalDateTime.now());
        //获取参数
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OmsOrder::getId, order.getOrderId());
        OmsOrder omsOrder = orderService.getOne(lqw);
        if (omsOrder != null) {
            omsOrder.setDiscountAmount(order.getDiscountAmount());
            omsOrder.setFreightAmount(order.getFreightAmount());
            omsOrder.setStatus(order.getStatus());
        }
        orderService.updateById(omsOrder);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getOrderId());
        history.setCreateTime(LocalDateTime.now());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(order.getStatus());
        history.setNote("修改费用信息");
        operateHistoryService.save(history);
    }

    /**
     * 备注订单
     *
     * @param order
     */
    public void note(OmsOrder order) {
        //获取参数
        long id = order.getId();
        OmsOrder omsOrder = orderService.getById(id);
        omsOrder.setStatus(order.getStatus());
        omsOrder.setNote(order.getNote());
        order.setModifyTime(LocalDateTime.now());
        orderService.updateById(omsOrder);
        //添加关联表
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(id);
        history.setCreateTime(LocalDateTime.now());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(order.getStatus());
        history.setNote("修改备注信息：" + order.getNote());
        operateHistoryService.save(history);
    }

    /**
     * 修改收货人信息
     *
     * @param order
     */
    public void receiverInfo(OmsOrder order) {
        //设置时间
        order.setModifyTime(LocalDateTime.now());
        //创建条件构造器
        LambdaUpdateWrapper<OmsOrder> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(OmsOrder::getId, order.getOrderId());
        lqw.set(order.getReceiverCity() != null, OmsOrder::getReceiverCity, order.getReceiverCity());
        lqw.set(order.getReceiverName() != null, OmsOrder::getReceiverName, order.getReceiverName());
        lqw.set(order.getReceiverPhone() != null, OmsOrder::getReceiverPhone, order.getReceiverPhone());
        lqw.set(order.getReceiverPostCode() != null, OmsOrder::getReceiverPostCode, order.getReceiverPostCode());
        lqw.set(order.getReceiverProvince() != null, OmsOrder::getReceiverProvince, order.getReceiverProvince());
        lqw.set(order.getReceiverRegion() != null, OmsOrder::getReceiverRegion, order.getReceiverRegion());
        lqw.set(OmsOrder::getStatus, order.getStatus());
        orderService.update(lqw);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(LocalDateTime.now());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(order.getStatus());
        history.setNote("修改收货人信息");
        operateHistoryService.save(history);
    }

    /**
     * 获取订单详情：订单信息、商品信息、操作记录
     *
     * @param id
     * @return
     */
    public OrderDto findById(Long id) {
        //获取该id的订单信息
        OmsOrder order = orderService.getById(id);
        OrderDto orderDto = new OrderDto();
        BeanUtils.copyProperties(order, orderDto);
        //根据订单id获取关联表1
        LambdaQueryWrapper<OmsOrderItem> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OmsOrderItem::getOrderId, id);
        List<OmsOrderItem> orderItemList = orderItemService.list(lqw);

        //根据订单id获取关联表2
        LambdaQueryWrapper<OmsOrderOperateHistory> qw = new LambdaQueryWrapper<>();
        qw.eq(OmsOrderOperateHistory::getOrderId, id);
        List<OmsOrderOperateHistory> historyList = operateHistoryService.list(qw);

        //设置返回参数
        orderDto.setHistoryList(historyList);
        orderDto.setOrderItemList(orderItemList);

        return orderDto;
    }

    /**
     * 判断参数是姓名还是手机号
     *
     * @param str
     * @return
     */
    private Boolean isNumber(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
